import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ApiUrl} from '../../../../config/api-url';
import {PermissionParentComponent} from '../permission-parent/permission-parent.component';
import {BaseService} from '../../../../shared/service/base.service';
import {LayerService} from '../../../../shared/service/layer.service';

@Component({
  selector: 'app-permission-edit',
  templateUrl: './permission-edit.component.html',
  styleUrls: ['./permission-edit.component.less']
})
export class PermissionEditComponent implements OnInit {

  formModel: FormGroup;

  @Input()
  isVisible = false;
  @Input()
  platformType: any;

  superiorIsVisible = false;

  permissionId: string;

  @Output()
  emit: EventEmitter<any> = new EventEmitter();

  title = '添加权限';

  type = 'menu';
  isOkLoading = false;

  @Input() selfPermission;
  @Input() parentPermission;

  // 子页面，树形结构
  @ViewChild('parent', {read: PermissionParentComponent, static: true})
  public parent: PermissionParentComponent;

  constructor(private httpService: BaseService, private fb: FormBuilder, private layer: LayerService) {
    this.buildForm();
  }

  ngOnInit(): void {

  }

  ngOnChanges() {
    if (this.selfPermission != null) {
      this.title = '编辑权限';
      this.resetForm(this.selfPermission);
    } else {
      this.title = '添加权限';
      this.formModel.reset({
        type: '1',
        method: 'get',
        status: 1,
        openSetting: 0
      });
    }
  }

  updateTitle(value){
    if (!this.formModel.get('titleSimplify').value){
      this.formModel.get('titleSimplify').setValue(value);
    }
  }

  buildForm() {
    this.formModel = this.fb.group({
      id: [null, []],
      title: [null, [Validators.required]],
      titleSimplify: [null, [Validators.required]],
      nav: [true, []],
      type: ['1', []],
      url: [null, []],
      code: [null, []],
      method: ['get', []],
      noAuth: [false, []],
      parentId: [null, []],
      param: [null, []],
      sort: [null, []],
      icon: [null, []],
      status: [1, [Validators.required]],
      openSetting: [0, [Validators.required]],
    });
  };

  resetForm(permission) {
    this.formModel.reset({
      id: permission.id,
      title: permission.title,
      titleSimplify: permission.titleSimplify,
      nav: permission.nav,
      type: permission.type,
      url: permission.url,
      code: permission.code,
      noAuth: permission.noAuth,
      method: permission.method,
      parentId: permission.parentId,
      param: permission.param,
      sort: permission.sort,
      icon: permission.icon,
      status: permission.status,
      openSetting: permission.openSetting,
    });
  }

  showParentMenus() {
    if (this.formModel.get("id").value != null ){
      this.permissionId  = this.formModel.get("id").value;
    }
    this.superiorIsVisible = true;
  }

  setVisible(body) {
    console.log('收到的Body:', body);
    this.superiorIsVisible = body.isVisible;
    this.permissionId = null;

    if (body.menu != undefined) {
      this.parentPermission = body.menu;
      this.parentPermission.id = body.menu.key;
    }
  }

  handleCancel(): void {
    this.isVisible = false;
    this.formModel.reset({});
    this.selfPermission = null;
    let body = {'isVisible': this.isVisible};
    this.emit.emit(body);
  }

  handleOk(): void {


    if (!this.httpService.zorro.validateFormValidate(this.formModel)) {
      return;
    }
    this.isOkLoading = true;
    if (!this.isOkLoading) {
      return;
    }

    if (!this.formModel.valid) {
      this.isOkLoading = false;
      return;
    }

    this.formModel.value.parentId = this.parentPermission.id;

    if (this.type == 'url') {
      this.formModel.value.nav = false;
    }

    if (this.type == 'menu') {
      this.formModel.value.method = null;
    }

    if (this.selfPermission == null) {
      this.add();
    } else {
      this.update();
    }
  }

  add() {
    // console.log("platformType", this.platformType)
    this.formModel.value.platformType = this.platformType;
    // console.log("platformType", this.formModel.value.platformType)
    this.httpService.post(ApiUrl.PermissionUrl, this.formModel.value).subscribe(
      data => {
        if (data.status == 0) {
          this.layer.messageSuccess('添加权限成功！');
        } else {
          this.layer.messageError('添加权限失败！');
        }
        this.commonHandle();
      }
    );
  }

  update() {
    this.httpService.put(ApiUrl.PermissionUrl, this.formModel.value).subscribe(
      data => {
        if (data.status == 0) {
          this.layer.messageSuccess('权限更新成功！');
        } else {
          this.layer.messageError('添加更新失败！');
        }
        this.commonHandle();
      }
    );
  }

  commonHandle() {
    this.isOkLoading = false;
    this.isVisible = false;
    let body = {'isVisible': this.isVisible, 'refresh': false};
    this.emit.emit(body);
    this.parent.getSimpleMenus();
  }


  changeType(value) {
    if (value == 1) {
      this.type = 'menu';
      this.formModel.value.nav = false;
      this.setValidity('clear');
    } else {
      this.type = 'url';
      this.formModel.value.nav = true;
      this.setValidity('set');
    }
  }

  setValidity(fun) {
    let url = this.formModel.get('url');
    let title = this.formModel.get('title');

    if (fun == 'set') {
      url.setValidators(Validators.required);
    } else {
      url.clearValidators();
      url.updateValueAndValidity();
    }

    title.markAsPristine();
    title.updateValueAndValidity();
  }

}
